package com.water.wfo.component.api.filter;


import com.water.wfo.component.api.interceptor.AuthenticationInterceptor;
import com.water.wfo.component.util.StringUtil;
import com.water.wfo.user.pojo.context.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import java.io.IOException;


/**
 * packageName com.water.wfo.component.api.filter
 *
 * @author
 * @className CommonFilter(处以class为网)
 * @date 2025/1/16
 * @description T0D0
 */
@Slf4j
@Component
@Order(1)
@WebFilter(filterName="commonFilter",urlPatterns="/*")
public class CommonFilter implements Filter {

    public CommonFilter(){

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.debug("Common Filter start...");
        synchronized (Object.class){
        }
        Cookie cookie = AuthenticationInterceptor.getCookie();
        if(null != cookie){
            String paramToken = cookie.getValue();
            paramToken = StringUtil.replace(paramToken,"-","+");
            paramToken = StringUtil.replace(paramToken,"_","/");
            String token= new String(Base64.decodeBase64(paramToken),"UTF-8");
            String[] keys = token.split(",");
            String userId = keys[1];
            String deptCode = keys[3];
            //设置用户信息
            //UserContext.setCurrentUser();
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.remove();
        }
        log.debug("Common Filter doFilter...");
        log.debug("Common Filter end...");
    }

    @Override
    public void destroy() {

    }
}
